package com.project.lk.nurseapp.bloodglucose;

import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattService;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.icu.text.UnicodeSetSpanner;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.Description;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.project.lk.nurseapp.R;
import com.project.lk.nurseapp.base.BaseActivity;
import com.project.lk.nurseapp.bloodglucose.presenter.IPostGlucoseView;
import com.project.lk.nurseapp.bloodglucose.presenter.PostGlucosePresenter;
import com.project.lk.nurseapp.common.adapter.TypeItemAdapter;
import com.project.lk.nurseapp.common.bean.TypeItemBean;
import com.project.lk.nurseapp.common.view.PercentView;
import com.project.lk.nurseapp.common.view.bluetooth.BleManager;
import com.project.lk.nurseapp.common.view.bluetooth.BluetoothListActivity;
import com.project.lk.nurseapp.utils.AppManager;
import com.project.lk.nurseapp.utils.ByteToStringUtils;
import com.project.lk.nurseapp.utils.PopWindowManager;
import com.project.lk.nurseapp.utils.SharedPreferencesUtils;
import com.project.lk.nurseapp.utils.TimeUtils;
import com.project.lk.nurseapp.utils.ToastUtils;
import com.project.lk.nurseapp.utils.TypeUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
/**
 * 功能介绍：蓝牙模块方法调用基本一样，血糖计测量界面
 * 项目名：
 * 模块名称：
 * 作者：LK
 * 日期：2018/1/9
 * 修改日期：
 */
public class BloodGlucoseActivity extends BaseActivity implements IPostGlucoseView{


    @BindView(R.id.hint_tv)
    TextView hintTv;
    @BindView(R.id.time_tv)
    TextView timeTv;
    @BindView(R.id.blood_num_tv)
    TextView bloodNumTv;
    @BindView(R.id.type_recyclerview)
    RecyclerView typeRecyclerview;
    @BindView(R.id.record_recyclerview)
    RecyclerView recordRecyclerview;
    @BindView(R.id.glucose_chart)
    LineChart glucoseChart;
    @BindView(R.id.percentView)
    PercentView percentView;
    private View praentView;
    private View blueContentView;
    private PopupWindow bluePopupWindow;
    private BleManager bleManager;
    private PostGlucosePresenter presenter;
    private List<TypeItemBean> typeItemBeanList;
    private TypeItemAdapter typeAdapter;

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
    @Override
    protected void initData() {
        //初始化蓝牙服务器类
        bleManager = BleManager.init();
        bleManager.initialize();
        String login = getIntent().getStringExtra("login");
        if (TextUtils.equals(login,"login")) {
            presenter = new PostGlucosePresenter(this);
        }
    }

    @Override
    protected void initView() {
        typeItemBeanList = new ArrayList<>();
        for (int i=0;i<typeStr.length;i++){
            TypeItemBean typeItemBean = new TypeItemBean();
            typeItemBean.setColor(typeColor[i]);
            typeItemBean.setSelect(false);
            typeItemBean.setTitle(typeStr[i]);
            typeItemBeanList.add(typeItemBean);
        }
        typeAdapter = new TypeItemAdapter(typeItemBeanList,this);
        StaggeredGridLayoutManager manager=new StaggeredGridLayoutManager(typeStr.length,StaggeredGridLayoutManager.VERTICAL);
        typeRecyclerview.setAdapter(typeAdapter);
        typeRecyclerview.setLayoutManager(manager);
        setBluetoothPopwind();
        YData.clear();
        YData.add(Float.valueOf(0));
        setLineChart(); //设置默认数据
        percentView.setAngel(5*10);
    }

    @Override
    protected void onResume() {
        super.onResume();
  Boolean isConn = (Boolean) SharedPreferencesUtils.getParam("Glucose", false);  //通过share保存连接当前设备的状态来判断是否可以测量
        if (isConn) {
            hintTv.setText("已连接");
        }else {
            hintTv.setText("未连接");
        }
        registerReceiver(mGattUpdateReceiver, makeGattUpdateIntentFilter());
    }

    private static IntentFilter makeGattUpdateIntentFilter() {
        final IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BleManager.ACTION_GATT_CONNECTED);
        intentFilter.addAction(BleManager.ACTION_GATT_DISCONNECTED);
        intentFilter.addAction(BleManager.ACTION_GATT_SERVICES_DISCOVERED);
        intentFilter.addAction(BleManager.ACTION_DATA_AVAILABLE);
        return intentFilter;
    }
    /*广播回调*/
    StringBuilder builder1=new StringBuilder(14);
    private final BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver() {
        @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
        @Override
        public void onReceive(Context context, Intent intent) {
            final String action = intent.getAction();
            if (BleManager.ACTION_GATT_CONNECTED.equals(action)) {
                Log.e("MLOG","ACTION_GATT_CONNECTED");
//                hintTv.setText("已连接");
            } else if (BleManager.ACTION_GATT_DISCONNECTED.equals(action)) {  //蓝牙断开回调
                Log.e("MLOG","ACTION_GATT_DISCONNECTED");
                 SharedPreferencesUtils.setParam("Glucose",false);
                hintTv.setText("未连接");
            } else if (BleManager.ACTION_GATT_SERVICES_DISCOVERED.equals(action)) { //蓝牙连接成功回调
                // Show all the supported services and characteristics on the user interface.
                List<BluetoothGattService> supportedGattServices = bleManager.getSupportedGattServices();
                showList(supportedGattServices);
                infoBluetooth(); //设置蓝牙服务可读可写
                bleManager.initNotify(); //刷新消息
            } else if (BleManager.ACTION_DATA_AVAILABLE.equals(action)) {   //获取蓝牙设备发给app的数据
                if (intent.getStringExtra(BleManager.EXTRA_DATA)!=null) {
                    Log.e("MLOG",intent.getStringExtra(BleManager.EXTRA_DATA));
                    String codeGlucose = intent.getStringExtra(BleManager.EXTRA_DATA);
                    String  glucose=null;
                   String[] splitGlucose = codeGlucose.toString().split(" ");
                    for (int i=0;i<splitGlucose.length;i++){
                        if (TextUtils.equals(splitGlucose[i],"0C")){
                            if ((i+3<splitGlucose.length)) {
                                glucose = splitGlucose[i+2] + splitGlucose[i+3];
                            }
                        }
                    }
                    if (glucose!=null) {
                        String glucoseStr = ByteToStringUtils.hex16StrTo10Str(glucose);
                        bloodNumTv.setText(String.valueOf(Math.round((Float.parseFloat(glucoseStr) / 18) * 10) * 0.1));
                        timeTv.setText(TimeUtils.getSateTime(new Date()));
                        YData.add(Float.parseFloat(glucoseStr));
                        setLineChart();
                    }
                    //TODO:上传数据到服务器。。。
//                            if (presenter!=null) {
//                                presenter.postTemDate(new UserInfoUtils().getHealthUrl()+ UrlContants.POST_TEM_URL,
//                                        thermomterStr,TypeUtils.getThermomterStr(thermomterStr),TimeUtils.getSateTime(new Date()));
//                            }

                }

            }
        }
    };

    /*获取蓝牙服务列表*/
    List<BluetoothGattCharacteristic> mBluetoothList=new ArrayList<>();
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
    public void showList(List<BluetoothGattService> gattServices){
        for (BluetoothGattService gattService : gattServices) {
            List<BluetoothGattCharacteristic> gattCharacteristics =
                    gattService.getCharacteristics();
            for (BluetoothGattCharacteristic gattCharacteristic : gattCharacteristics) {
                mBluetoothList.add(gattCharacteristic);
            }
        }
    }
    /*遍历蓝牙服务，设置蓝牙服务可读可写*/
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
    public void infoBluetooth(){
        for (BluetoothGattCharacteristic characteristic : mBluetoothList){
            bleManager.setCharacteristicNotification(
                    characteristic, false);
        }

    }
    List<Float> YData=new ArrayList<>();
    private void setLineChart() {
        List<Entry> entries = new ArrayList<Entry>();
        for (int i=0;i<YData.size();i++){
            entries.add(new Entry(i,YData.get(i)));
        }
        Description description = new Description();
        description.setText("最近测量的血糖");//描述文字
//description.setPosition(50f,50f);//文字位置，默认图表右下角
        description.setTextColor(Color.RED);//描述文字字体颜色
        LineDataSet dataSet = new LineDataSet(entries, "血糖仪"); // add entries to dataset
        dataSet.setColor(Color.RED);
        dataSet.setCircleColor(Color.RED);
        dataSet.setDrawValues(false);
        LineData lineData = new LineData(dataSet);
        glucoseChart.setDescription(description);
        glucoseChart.setData(lineData);
        glucoseChart.invalidate(); // refresh
        //获取右边的轴线
        YAxis rightAxis=glucoseChart.getAxisRight();
        //设置图表右边的y轴禁用
        rightAxis.setEnabled(false);
        XAxis xAxis = glucoseChart.getXAxis();
        xAxis.setEnabled(true);//设置轴启用或禁用 如果禁用以下的设置全部不生效
        xAxis.setDrawAxisLine(true);//是否绘制轴线
        xAxis.setDrawGridLines(true);//设置x轴上每个点对应的线
        xAxis.setDrawLabels(true);//绘制标签  指x轴上的对应数值
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);//设置x轴的显示位置
    }
    //设置弹窗
    private void setBluetoothPopwind() {
        praentView = LayoutInflater.from(this).inflate(R.layout.activity_msg_list, null);
        blueContentView = LayoutInflater.from(this).inflate(R.layout.bluetooth_popwind_layout, null);
        bluePopupWindow = new PopupWindow(blueContentView,
                LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT, true);

        Button cancelBut = (Button) blueContentView.findViewById(R.id.cancel_but);
        Button commentBut = (Button) blueContentView.findViewById(R.id.setting_but);


        //点击事件
        setEvent(cancelBut, commentBut, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (v.getId()) {
                    case R.id.cancel_but: //取消
                        bluePopupWindow.dismiss();
                        break;
                    case R.id.setting_but:  //设置
                        bluePopupWindow.dismiss();
                        startActivity(new Intent(BloodGlucoseActivity.this, BluetoothListActivity.class));
                        break;
                }

            }
        });
    }
    //设置点击事件
    private void setEvent(Button cancelBut, Button commentBut, View.OnClickListener listener) {
        cancelBut.setOnClickListener(listener);
        commentBut.setOnClickListener(listener);
    }
    int[] typeColor=new int[]{
            R.color.blue,R.color.green,
            R.color.little_green,
            R.color.orange,
            R.color.red};
    String [] typeStr=new String[]{"较低","偏低","正常","偏高","较高"};
    @Override
    protected int getLayoutId() {
        return R.layout.activity_blood_glucose;
    }

    boolean isMeasure=false;
    String measureType="";
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
    @OnClick({R.id.back, R.id.before_but, R.id.after_but, R.id.record_tv,R.id.hint_tv})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back:
                AppManager.getAppManager().finishActivity();
                break;
            case R.id.before_but: //选择餐前状态

                break;
            case R.id.after_but: //选择餐后测量


                break;
            case R.id.record_tv: //历史记录
                startActivity(new Intent(this,BloodGlucoseHistoryActivity.class));
                break;
            case R.id.hint_tv: //弹窗
                if (hintTv.getText().equals("未连接")){

                    PopWindowManager.showAsLocationWindow(praentView,blueContentView,bluePopupWindow,R.id.bluetooth_popwind_layout);
                }
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (bleManager!=null) {
            bleManager.disableBlueBle("Glucose");//关闭蓝牙
        }
        if (mGattUpdateReceiver!=null) {
            unregisterReceiver(mGattUpdateReceiver);
        }
        if (presenter!=null) {
            presenter.dettachView();
            presenter=null;
        }
    }

    @Override
    public void postSuccess() {

    }

    @Override
    public void postFail() {

    }
}
